import React, { useEffect, useState } from 'react'
import { NoteWithRelations } from '../types/serviceTypes.ts'

import AuthorCard from './AuthorCard.tsx'
import NoteContent from './NoteContent.tsx'
import DisplayContent from './DisplayContent.tsx'
import ExpandButton from './ExpandButton.tsx'
import { Button, Card, Divider, message, Popconfirm } from 'antd'
import OptionsCard from './OptionsCard.tsx'
import { DeleteOutlined, FormOutlined } from '@ant-design/icons'
import NoteWritePage from '@/apps/user/pages/NoteWritePage.tsx'
import { noteService } from '@/domain/note/service/noteService.ts'

interface NoteItemProps {
  note?: NoteWithRelations
  setNoteLikeStatus?: (noteId: number, isLiked: boolean) => void
  /** 控制模态框的展示 */
  toggleIsModalOpen: () => void
  /** 设置查询收藏夹参数和设置被选中的笔记 ID */
  handleCollectionQueryParams: (noteId: number) => void
  handleSelectedNoteId: (noteId: number) => void
  /** 控制组件信息展示 */
  showAuthor?: boolean // 是否展示作者信息
  showCategory?: boolean // 是否展示题目信息
  showOptions?: boolean // 是否展示点赞/收藏/评论等按钮
  showAdminOptions?: boolean // 是否展示管理按钮
  onRefresh?: () => void
}

const NoteItem: React.FC<NoteItemProps> = ({
  note,
  setNoteLikeStatus,
  showAuthor = true,
  showOptions = true,
  showAdminOptions = false,
  showCategory = true,
  toggleIsModalOpen,
  handleCollectionQueryParams,
  handleSelectedNoteId,
  onRefresh,
}) => {
  const [isCollapsed, setIsCollapsed] = useState(false)

  const toggleCollapsed = () => {
    setIsCollapsed(!isCollapsed)
  }

  const [isUpgrading, setIsUpgrading] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    // 当 note 加载完成时更新状态
    if (note) {
      setIsLoading(false)
      if (note.needCollapsed) {
        setIsCollapsed(true)
      }
    } else {
      setIsLoading(true)
    }
  }, [note])

  const handleCancelUpgrading = () => {
    setIsUpgrading(false)
  }
  const handleDelete = async (noteId: number) => {
    const resp = await noteService.deleteNoteService(noteId)
    if (!resp) {
      message.error('删除失败')
    } else {
      message.success('删除成功')
    }
  }
  if (!isUpgrading) {
    return (
      <>
        {
          <>
            <div className="flex w-full flex-col gap-4">
              {showAuthor && <AuthorCard note={note} isLoading={isLoading} />}
              {showCategory && (
                <Card
                  title={
                    note?.category ? note?.category?.categoryName : '未分类'
                  }
                ></Card>
              )}
              {isCollapsed ? (
                <DisplayContent displayContent={note?.displayContent ?? ''} />
              ) : (
                <NoteContent note={note} />
              )}
              {note?.needCollapsed && (
                <ExpandButton
                  toggleCollapsed={toggleCollapsed}
                  isCollapsed={isCollapsed}
                  key={note?.noteId}
                />
              )}
              {showOptions && (
                <OptionsCard
                  note={note}
                  setNoteLikeStatus={setNoteLikeStatus}
                  toggleIsModalOpen={toggleIsModalOpen}
                  handleCollectionQueryParams={handleCollectionQueryParams}
                  handleSelectedNoteId={handleSelectedNoteId}
                  onRefresh={onRefresh}
                />
              )}
              {showAdminOptions && (
                <div className="justify-begin sticky bottom-0 z-20 flex gap-5">
                  <Button
                    icon={<FormOutlined />}
                    onClick={() => setIsUpgrading(true)}
                  >
                    修改笔记
                  </Button>
                  <Popconfirm
                    title="确定要删除这篇笔记吗？"
                    onConfirm={() => handleDelete(note?.noteId as number)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button danger icon={<DeleteOutlined />}>
                      删除笔记
                    </Button>
                  </Popconfirm>
                </div>
              )}
            </div>
            <Divider />
          </>
        }
      </>
    )
  } else {
    return (
      <>
        {
          <>
            <NoteWritePage
              isUpgrading={isUpgrading}
              onCancelUpgrading={handleCancelUpgrading}
              currentNoteId={note?.noteId}
              currentNoteValue={note?.content}
              currentIsPublic={note?.isPublic}
              currentCategoryName={note?.category?.categoryName}
              currentCategoryId={note?.category?.categoryId}
            ></NoteWritePage>
            <Divider />
          </>
        }
      </>
    )
  }
}

export default NoteItem
